package entity_controllers.fieldcontrollers;

import boundary.UI;
import ie.FieldBoard;
import ie.PlayerBoard;
import ie.Shaker;
import controllers.FieldController;
import desktop_resources.GUI;
import dto.Field;
import dto.Player;
import entity_controllers.Card;
import entity_controllers.cards.FreeJailCard;

public class ChanceController extends FieldController {

	private static Card[] cards;
	private static int index = 0;

	// Constructor creates an array of cards, with length 29
	public ChanceController(Card ... cards) {
		if (ChanceController.cards == null) {
			ChanceController.cards = cards;
			mixCards();
		}
	}

	public void mixCards() {
		Card temp;
		int index;
		for (int i = cards.length - 1; i >= 0; i--) {
			index = (int) (Math.random() * (i + 1));
			temp = cards[index];
			cards[index] = cards[i];
			cards[i] = temp;
		}
	}


	@Override
	public void execute(Player player, Field field, FieldBoard fieldBoard, PlayerBoard playerBoard, Shaker shaker) {
		// The top card is drawn and is assigned to the variable "chance"
		int drawnCardIndex = index;
		Card drawnCard = cards[drawnCardIndex];
		
		if (drawnCard.getClass().equals(FreeJailCard.class)) {
			cards[drawnCardIndex] = null;
			for (int i = drawnCardIndex; i > 0; i--) {
				cards[i] = cards[i-1];
			}
		}

		Card nextCard;
		do {
			index++;
			index %= cards.length;
			nextCard = cards[index];
		} while (nextCard == null);

		UI.get().showCard(drawnCard.getCardText());
		UI.get().getMessage("Prøv lykken, tag et kort");

		// The drawn card is put below the deck, thus pushing all other cards one index down		
		// The logic of the drawn card is executed
		drawnCard.execute(player, fieldBoard, playerBoard, shaker);
	}

	// this is a temporary "Player Card" fix. Should be reimplemented if using more "hand held" cards.
	public static void putBackCard() {
		for (int i = 0; i < cards.length - 1; i++) {
			if (cards[i + 1] != null) {
				cards[i] = new FreeJailCard();
				break;
			}
		}
	}

}
